package com.imoblife.brainwavestus.oldDownloadFrame;

import java.text.SimpleDateFormat;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.util.Log;

import com.googleplay.billing.BillingService;
import com.googleplay.billing.BillingService.RequestPurchase;
import com.googleplay.billing.BillingService.RestoreTransactions;
import com.googleplay.billing.Consts.PurchaseState;
import com.googleplay.billing.Consts.ResponseCode;
import com.googleplay.billing.PurchaseObserver;
import com.googleplay.billing.ResponseHandler;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItem;
import com.imoblife.brainwavestus.service.DownLoadSchedulerSystem;
import com.imoblife.brainwavestus.service.DownloadService;
import com.imoblife.brainwavestus.util.DebugUtil;

public class RestoreTransactionsTask extends DownLoadItem {
	static DownLoadSchedulerSystem downLoadSchedulerSystem;
	private BillingService mBillingService;
	private static final String TAG = "RestoreTransactionsTask";
	RestoreTransactionsObserver mRestoreTransactionsObserver;
	private Handler mHandler;
	Context mContext;
	private static boolean isRestoreEnd = true;

	private boolean isSuccess = false;

	private class RestoreTransactionsObserver extends PurchaseObserver {

		public RestoreTransactionsObserver(Context context, Handler handler) {
			super(context, handler);
			mContext = context;
		}

		public void onBillingSupported(boolean supported, String type) {
			DebugUtil.debug(TAG, "supported: " + supported);
			DebugUtil.debug(TAG, "onBillingSupported >> type : " + type);
			if (!supported) {
				isRunning = false;
				isSuccess = true;
				isRestoreEnd = true;
			}

		}

		public void onPurchaseStateChange(PurchaseState purchaseState,
				String itemId, int quantity, long purchaseTime,
				String developerPayload) {
			DebugUtil.debug(TAG, "onPurchaseStateChange >> purchaseState : "
					+ purchaseState);
			DebugUtil.debug(TAG, "onPurchaseStateChange() itemId: " + itemId
					+ " " + purchaseState);
			DebugUtil.debug(TAG, "onPurchaseStateChange >> quantity : "
					+ quantity);
			DebugUtil.debug(TAG, "onPurchaseStateChange >> purchaseTime : "
					+ new SimpleDateFormat("MM-dd-yyyy").format(purchaseTime));
			DebugUtil.debug(TAG, "onPurchaseStateChange >> developerPayload : "
					+ developerPayload);
			isRunning = false;
			isRestoreEnd = true;
		}

		public void onRequestPurchaseResponse(RequestPurchase request,
				ResponseCode responseCode) {

			DebugUtil.debug(TAG, request.mProductId + ": " + responseCode);

			if (responseCode == ResponseCode.RESULT_OK) {

				DebugUtil.debug(TAG, "purchase was successfully sent to server");
			} else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {

				DebugUtil.debug(TAG, "user canceled purchase");

			} else {
				DebugUtil.debug(TAG, "purchase failed");
			}
		}

		public void onRestoreTransactionsResponse(RestoreTransactions request,
				ResponseCode responseCode) {

			if (responseCode == ResponseCode.RESULT_OK) {
				isSuccess = true;
				confirmRestoreTransations(mContext);
				DebugUtil.debug(TAG, "�ָ��˵� �ɹ�");
			} else {
				isSuccess = false;

				DebugUtil.debug(TAG, "�ظ��˵�ʧ�� responseCode=" + responseCode);
			}
			isRunning = false;
			isRestoreEnd = true;
		}
	}

	public RestoreTransactionsTask(
			DownLoadSchedulerSystem downLoadSchedulerSystem) {
		super("RestoreTransactions", "RestoreTransactions");
		this.downLoadSchedulerSystem = downLoadSchedulerSystem;
	}
	
	//加这个方法只是为了测试通过，后续需要整改这个类
	public RestoreTransactionsTask(
			DownloadService downService) {
		super("RestoreTransactions", "RestoreTransactions");

	}
	
	public RestoreTransactionsTask() {
		super("RestoreTransactions", "RestoreTransactions");
	}

	public void run() {

		synchronized (RestoreTransactionsTask.class) {

			try {
				if (checkRestoreTransactions()) {
					initRestoreTransactions();
					DebugUtil.debug(TAG, "�ָ��˵����===================");
					if (mBillingService.checkBillingSupported()) {

						mBillingService.restoreTransactions();

						int count = 0;
						try {
							while (isRunning && count < 20) {
								DebugUtil.debug(TAG, "�ָ��˵����");
								Thread.sleep(1000);
								count++;
							}

						} catch (InterruptedException e) {

							e.printStackTrace();
						}
					}

					destroyRestoreTransactions();

				}
				OBpurchaseSystem.getOBpurchaseSystem(downLoadSchedulerSystem)
						.restoreTransactions(downLoadSchedulerSystem);

			} catch (Exception e) {

			}
		}
	}

	static Boolean sycn = true;

	public boolean promptRestoreTransactions(Activity activity) {

		synchronized (sycn) {
			DebugUtil.debug(TAG,
					">>>>>>>>>>>>>>>>>>>>promptRestoreTransactions start");
			boolean result = false;
			try {
				initUserRestoreTransactions(activity);

				if (mBillingService.checkBillingSupported()) {

					mBillingService.restoreTransactions();

					int count = 0;
					try {
						while (isRunning && count < 20) {

							Thread.sleep(1000);
							count++;
						}

					} catch (InterruptedException e) {

						e.printStackTrace();
					}
					result = isSuccess;

				} else {
					result = true;
				}

				destroyRestoreTransactions();

				boolean tapjoyResult = (OBpurchaseSystem
						.getOBpurchaseSystem(activity)
						.promptRestoreTransactions(activity));

				DebugUtil.debug(TAG,
						">>>>>>>>>>>>>>>>>>>>promptRestoreTransactions end");

				return tapjoyResult && result;

			} catch (Exception e) {

				e.printStackTrace();
			}
			DebugUtil.debug(TAG,
					">>>>>>>>>>>>>>>>>>>>promptRestoreTransactions end");
			return false;
		}

	}

	public boolean restoreTransactions(Activity activity) {

		synchronized (sycn) {
			DebugUtil.debug(TAG,
					">>>>>>>>>>>>>>>>>>>>restoreTransactions start");
			boolean result = false;
			try {
				initRestoreTransactions();

				if (mBillingService.checkBillingSupported()) {

					mBillingService.restoreTransactions();

					int count = 0;
					try {
						while (isRunning && count < 20) {

							Thread.sleep(1000);
							count++;
						}

					} catch (InterruptedException e) {

						e.printStackTrace();
					}
					result = isSuccess;

				} else {
					result = true;
				}

				destroyRestoreTransactions();

				boolean tapjoyResult = (OBpurchaseSystem
						.getOBpurchaseSystem(activity)
						.restoreTransaction(activity));

				DebugUtil.debug(TAG,
						">>>>>>>>>>>>>>>>>>>>promptRestoreTransactions end");

				return tapjoyResult && result;

			} catch (Exception e) {

				e.printStackTrace();
			}
			DebugUtil.debug(TAG,
					">>>>>>>>>>>>>>>>>>>>promptRestoreTransactions end");
			return false;
		}

	}

	public String serverBillingRestore(Context context, String lock) {
		String response = (OBpurchaseSystem.getOBpurchaseSystem(context)
				.userRestoreTransactions(lock));
		return response;
	}

	public String serverBillingRestore2(Context context, String lock) {
		String response = (OBpurchaseSystem.getOBpurchaseSystem(context)
				.userRestoreTransactions2(lock));
		return response;
	}

	public void marketBillingRestore(Activity activity) {

		synchronized (RestoreTransactionsTask.class) {
			if (isRestoreEnd) {
				isRestoreEnd = false;
				Handler handler = new Handler();
				RestoreTransactionsObserver marketBillngRestoreObserver = new RestoreTransactionsObserver(
						activity, handler);
				mBillingService = new BillingService();
				mBillingService.setContext(activity);
				ResponseHandler.register(marketBillngRestoreObserver);
				if (mBillingService.checkBillingSupported()) {
					mBillingService.restoreTransactions();
				}
				
			}
		}
	}

	public void destroyMarketBillingRestore() {
		ResponseHandler.unregister(mRestoreTransactionsObserver);
		mBillingService.unbind();
	}

	public String userRestoreAndSendAllMusicBill(Context context) {
		String result = null;
		result = OBpurchaseSystem.getOBpurchaseSystem(context)
				.restoreTapjoyAndSendAllBill(context);
		return result;
	}

	void initRestoreTransactions() {
		mHandler = downLoadSchedulerSystem.updateUIHandler;
		mRestoreTransactionsObserver = new RestoreTransactionsObserver(
				downLoadSchedulerSystem, mHandler);
		mBillingService = new BillingService();
		mBillingService.setContext(downLoadSchedulerSystem);
		ResponseHandler.register(mRestoreTransactionsObserver);
	}

	void initUserRestoreTransactions(Activity activity) {
		mHandler = downLoadSchedulerSystem.updateUIHandler;
		mRestoreTransactionsObserver = new RestoreTransactionsObserver(
				activity, mHandler);
		mBillingService = new BillingService();
		mBillingService.setContext(activity);
		ResponseHandler.register(mRestoreTransactionsObserver);
	}

	void destroyRestoreTransactions() {

		ResponseHandler.unregister(mRestoreTransactionsObserver);
		mBillingService.unbind();

	}

	public int getLevel() {
		return 10;
	}

	private boolean checkRestoreTransactions() {

		return true;
	}

	private void confirmRestoreTransations(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(
				"RestoreTransactions", 1);
		preferences.edit().putLong("prevtime", System.currentTimeMillis())
				.commit();
	}

	public boolean isInterrupted() {

		return false;
	}

	public void interrupt() {

	}

	public String getTaskName() {

		return "RestoreTransactionsTask";
	}

	public boolean checkSupportGmail() {
		return getGmailAccount() != null;
	}

	public String[] getGmailAccount() {

		AccountManager accountManager = AccountManager
				.get(downLoadSchedulerSystem);

		if (accountManager == null) {
			return null;
		}
		Account[] accounts = accountManager.getAccountsByType("com.google");
		if (accounts == null || accounts.length < 1) {
			return null;
		}
		String[] accountName = new String[accounts.length];
		for (int i = 0; i < accounts.length; i++) {
			accountName[i] = accounts[i].name;
		}
		return accountName;
	}

}
